# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 学员端师生关系视图

学员选择教练、申请、管理的路由处理
包括搜索教练、查看详情、申请选择、关系管理等功能
"""

from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user

from app.controllers.relation_controller import RelationController
from app.models.user import User
from app.decorators import student_required

# 创建学员教练关系蓝图
student_coach_bp = Blueprint('student_coach', __name__)


@student_coach_bp.route('/search')
@login_required
@student_required
def search():
    """
    搜索教练页

    学员可以搜索、筛选和浏览可选择的教练
    """
    # 获取搜索参数
    keyword = request.args.get('keyword', '')
    gender = request.args.get('gender', '')
    coach_level = request.args.get('coach_level', '')
    sort_by = request.args.get('sort_by', 'rating_desc')
    page = request.args.get('page', 1, type=int)
    per_page = 12

    # 搜索教练
    pagination, total = RelationController.search_coaches(
        student_id=current_user.id,
        keyword=keyword,
        gender=gender,
        coach_level=coach_level,
        sort_by=sort_by,
        page=page,
        per_page=per_page
    )

    # 为每个教练添加与当前学员的关系状态
    if pagination and pagination.items:
        from app.models.relation import StudentCoachRelation
        for coach in pagination.items:
            relation = StudentCoachRelation.query.filter_by(
                student_id=current_user.id,
                coach_id=coach.id
            ).first()

            if relation:
                coach.relation_status = relation.status
            else:
                coach.relation_status = None

    # 获取教练汇总信息
    summary = RelationController.get_coach_search_summary(current_user.campus_id)

    return render_template(
        'student_coach/search.html',
        coaches=pagination.items if pagination else [],
        pagination=pagination,
        keyword=keyword,
        gender=gender,
        coach_level=coach_level,
        sort_by=sort_by,
        summary=summary,
        total=total
    )


@student_coach_bp.route('/list')
@login_required
@student_required
def list():
    """
    教练列表页

    显示简化的教练列表，主要用于快速浏览
    """
    page = request.args.get('page', 1, type=int)
    per_page = 20

    # 获取教练列表
    pagination, total = RelationController.search_coaches(
        student_id=current_user.id,
        page=page,
        per_page=per_page
    )

    return render_template(
        'student_coach/list.html',
        coaches=pagination.items if pagination else [],
        pagination=pagination,
        total=total
    )


@student_coach_bp.route('/detail/<int:coach_id>')
@login_required
@student_required
def detail(coach_id):
    """
    教练详情页

    显示教练的详细信息、评价、课程信息等

    Args:
        coach_id: 教练ID
    """
    # 获取教练详情
    detail_info = RelationController.get_coach_detail(
        coach_id=coach_id,
        student_id=current_user.id
    )

    if not detail_info:
        flash('教练信息不存在或不可访问', 'error')
        return redirect(url_for('student_coach.search'))

    # 获取教练统计
    stats = RelationController.get_coach_statistics(coach_id)

    return render_template(
        'student_coach/detail.html',
        detail=detail_info,
        stats=stats
    )


@student_coach_bp.route('/apply/<int:coach_id>', methods=['GET', 'POST'])
@login_required
@student_required
def apply(coach_id):
    """
    申请选择教练页

    学员向教练提交选择申请

    Args:
        coach_id: 教练ID
    """
    # 先获取教练信息
    coach = User.query.filter_by(
        id=coach_id,
        role='coach',
        status='active'
    ).first()

    if not coach:
        flash('教练信息不存在或不可用', 'error')
        return redirect(url_for('student_coach.search'))

    if request.method == 'POST':
        apply_note = request.form.get('apply_note', '')

        # 提交申请
        success, message = RelationController.apply_coach(
            student_id=current_user.id,
            coach_id=coach_id,
            apply_note=apply_note
        )

        if success:
            flash(message, 'success')
            return redirect(url_for('student_coach.my_coaches'))
        else:
            flash(message, 'error')

    # 获取教练详情
    detail_info = RelationController.get_coach_detail(
        coach_id=coach_id,
        student_id=current_user.id
    )

    return render_template(
        'student_coach/apply.html',
        coach=coach,
        detail=detail_info
    )


@student_coach_bp.route('/my-coaches')
@login_required
@student_required
def my_coaches():
    """
    我的教练页

    显示学员已选择的教练列表和关系状态
    """
    # 获取已通过的教练关系
    approved_relations = RelationController.get_student_coaches(
        student_id=current_user.id,
        status='approved'
    )

    # 获取待审核的申请
    pending_relations = RelationController.get_student_coaches(
        student_id=current_user.id,
        status='pending'
    )

    return render_template(
        'student_coach/my_coaches.html',
        approved_relations=approved_relations,
        pending_relations=pending_relations
    )


@student_coach_bp.route('/applications')
@login_required
@student_required
def applications():
    """
    申请记录页

    显示学员的所有申请记录和状态
    """
    status = request.args.get('status', '')
    page = request.args.get('page', 1, type=int)
    per_page = 10

    # 获取申请记录
    pagination, total = RelationController.get_student_applications(
        student_id=current_user.id,
        status=status if status else None,
        page=page,
        per_page=per_page
    )

    return render_template(
        'student_coach/applications.html',
        applications=pagination.items if pagination else [],
        pagination=pagination,
        status=status,
        total=total
    )


@student_coach_bp.route('/cancel-application/<int:relation_id>', methods=['POST'])
@login_required
@student_required
def cancel_application(relation_id):
    """
    取消申请

    学员取消待审核的申请

    Args:
        relation_id: 关系ID
    """
    success, message = RelationController.cancel_application(
        student_id=current_user.id,
        relation_id=relation_id
    )

    if success:
        flash(message, 'success')
    else:
        flash(message, 'error')

    return redirect(url_for('student_coach.applications'))


@student_coach_bp.route('/remove-coach/<int:relation_id>', methods=['POST'])
@login_required
@student_required
def remove_coach(relation_id):
    """
    解除师生关系

    学员主动解除与教练的关系

    Args:
        relation_id: 关系ID
    """
    success, message = RelationController.remove_coach_relation(
        student_id=current_user.id,
        relation_id=relation_id
    )

    if success:
        flash(message, 'success')
    else:
        flash(message, 'error')

    return redirect(url_for('student_coach.my_coaches'))


@student_coach_bp.route('/api/coach-summary')
@login_required
@student_required
def api_coach_summary():
    """
    教练汇总信息API

    返回教练搜索的统计数据
    """
    try:
        summary = RelationController.get_coach_search_summary(current_user.campus_id)

        return jsonify({
            'success': True,
            'data': summary
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@student_coach_bp.route('/api/coach-detail/<int:coach_id>')
@login_required
@student_required
def api_coach_detail(coach_id):
    """
    教练详情API

    返回指定教练的详细信息

    Args:
        coach_id: 教练ID
    """
    try:
        detail_info = RelationController.get_coach_detail(
            coach_id=coach_id,
            student_id=current_user.id
        )

        if not detail_info:
            return jsonify({
                'success': False,
                'error': '教练信息不存在'
            }), 404

        # 转换数据格式以便JSON序列化
        coach_data = {
            'id': detail_info['coach'].id,
            'real_name': detail_info['coach'].real_name,
            'gender': detail_info['coach'].gender,
            'age': detail_info['coach'].age,
            'coach_level': detail_info['coach'].coach_level,
            'hourly_rate': str(detail_info['coach'].hourly_rate or 0),
            'bio': detail_info['coach'].bio or '',
            'photo_url': detail_info['coach'].photo_url,
            'created_at': detail_info['coach'].created_at.isoformat() if detail_info['coach'].created_at else None
        }

        return jsonify({
            'success': True,
            'data': {
                'coach': coach_data,
                'student_count': detail_info['student_count'],
                'total_classes': detail_info['total_classes'],
                'average_rating': detail_info['average_rating'],
                'total_reviews': detail_info['total_reviews'],
                'can_apply': detail_info['can_apply'],
                'application_status': detail_info['application_status']
            }
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500